<?php

include('include/header.php');

if (isset($_REQUEST[session_name()])) header("Location: /");

//Авторизация
if($_GET['action'] == 'login')
{
   //Проверака имени пользователя и пароля
   if(isset($_POST['user']) && $_POST['password'])
   {
      $mysql = mysql_connect("localhost", "root", "kGbN85Z");
      mysql_query("USE ftp;");

      $sql = "SELECT id FROM users WHERE login = '".mysql_real_escape_string($_POST['user'])."' AND password = MD5( '".mysql_real_escape_string($_POST['password'])."' );";

      //Авторизация прошла успешно
      if(mysql_num_rows(mysql_query($sql)))
      {
         session_start();
         $_SESSION['user'] = $_POST['user'];

         //Шифруем пароль
         $password = base64_encode($_POST['password']);

	 //Получаем новый пароль
	 $ftppass = GenPass(5);
         $_SESSION['ftppass'] = $ftppass;

	 //Меняем пароль к ftp
         mysql_query("USE proftpd;");
         mysql_query("REPLACE users ( username, password, uid, gid, homedir, shell ) VALUES ( '".mysql_real_escape_string($_POST['user'])."','".mysql_real_escape_string($ftppass)."', 5010, 5010, '/mnt/ftp', '/bin/nologin' );");

         //Устанавливаем куки
         SetCookie("user",$_POST['user'],time()+31536000);
         SetCookie("password",$password,time()+31536000);
         header("Location: http://".$_SERVER['HTTP_HOST']."/");
      }
      else
      {
         echo "Incorrect login or password<br>";
         echo "<a href=\"/\">Return</a>";
      }
   }
   else
   {
      ?>
      <html>
      <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
      <title>Авторизация</title>
      <body>
      <center>
      <form name="login" method="post" action="login.php?action=login">
      <p>Login: <input name="user" type="text" size="6"></p>
      <p>Password: <input name="password" type="password" size="6"></p>
      <p><input type="submit" value="Login"></p>
      </form>
      </center>
      <?
   }
}
//Выход
elseif($_GET['action'] == 'quit')
{
   session_start();
   setcookie("user","",time()-100);
   setcookie("password","",time()-100);
   setcookie("PHPSESSID","",time()-100);
   session_destroy();
   header("Location: http://".$_SERVER['HTTP_HOST']."/");
}

include('include/footer.php');

?>

</body>
</html>
